<!-- 1.放在29的根目录(跟api.php,apisub.php等在同一个目录)
2.更改一下文件名 以防别人乱搞(改成你自己知道的名字.php) -->


<?php
include('confing/common.php');

// 设置配置参数
$url = "https://feike.sbs";//你的站点地址比如：https://feike.sbs
$hid = 1139; // 对接本站的货源id，一般在货源页面查看，填错了会有问题请自行检查
$pricee = 7; // 5代表蜜雪冰城系统如果你的顶级费率是0.2，填5=跟源站价格完全相同，其他自行倍数计算 (建议修改为6)
$dockcro = 1; // 是否新建分类填1会克隆源站的所有分类，填0只会上架商品
$skipCategories = array('1', '9999'); // 替换成您实际要跳过的上游分类 ID 格式以此类推，填了代表不上架也不更新这几个分类的项目
$sleepTime = 1800; // 每次执行后休眠时间（秒），默认30分钟
$defaultMethod = 'yijiankelong'; // 守护进程默认执行的方法: 'yijiankelong'=一键克隆, 'gengxinjiage'=仅更新价格

// 关键词替换配置 - 格式: '原关键词' => '替换后的关键词'
$keywordReplacements = array(
    '蜜雪冰城' => '优品冰城',    // 例如：将"蜜雪冰城"替换为"优品冰城"
    '官方' => '平台',          // 例如：将"官方"替换为"平台"
    '原价' => '售价',          // 例如：将"原价"替换为"售价"
    'PUP' => '飞课自营',
    '卧龙' => '凤雏',
    '棚子' => '凤雏',
    '慢热' => '橘柚',
    '青青' => '摘星',
    'tenu' => '西南',
    '梦想' => '长温',
    '奶昔' => '久幸',
    '神秘' => '某某',
    '冷门' => '志友',
    '波妞' => '蓝澈',
    'yyy' => 'YYY继续教育',
    // 在此添加更多替换规则...
);
$enableKeywordReplacement = true; // 是否启用关键词替换：true=启用，false=禁用

// 检测是否通过GET方式访问
$act = isset($_GET['act']) ? daddslashes($_GET['act']) : null;

// 如果是通过GET访问，执行相应操作
if ($act) {
    // 处理cookie操作
    if ($act == 'cookie') {
        qcookie();
        exit;
    }
    
    // 处理一键克隆操作
    elseif ($act == 'yijiankelong') {
        // 获取货源信息
        $a = $DB->get_row("SELECT * FROM qingka_wangke_huoyuan WHERE hid='{$hid}'");
        if (!$a) {
            jsonReturn(-1, "货源信息不存在");
        }
        
        $data = array("uid" => $a["user"], "key" => $a["pass"]);
        $er_url = "{$a["url"]}/api.php?act=getclass";
        $result = get_url($er_url, $data);
        $result1 = json_decode($result, true);
        
        if (json_last_error() !== JSON_ERROR_NONE || !isset($result1["data"])) {
            jsonReturn(-1, "API 返回数据格式错误或缺失");
        }
        
        $categories = $result1["data"];
        $numItemsInserted = 0;
        $numItemsUpdated = 0;
        
        // 处理分类数据
        if ($dockcro == 1) {
            foreach ($categories as $value) {
                if (in_array($value['fenlei'], $skipCategories)) {
                    continue;
                }
                
                if (empty($category) || $value['fenlei'] == $category) {
                    // 应用关键词替换到分类名称
                    $fenleiname = $value['fenleiname'];
                    if ($enableKeywordReplacement) {
                        $fenleiname = str_replace(array_keys($keywordReplacements), array_values($keywordReplacements), $fenleiname);
                    }
                    
                    // 如果分类名为空则跳过
                    if (empty($fenleiname)) {
                        continue;
                    }
                    
                    $existingCategory = $DB->get_row("SELECT * FROM qingka_wangke_fenlei WHERE id='{$value['fenlei']}'");
                    if (!$existingCategory) {
                        // 新增分类时，使用上游分类的状态
                        $status = isset($value['status']) ? $value['status'] : '1';
                        $DB->query("INSERT INTO qingka_wangke_fenlei (id, sort, name, status, time) VALUES ('{$value['fenlei']}', '0', '{$fenleiname}', '{$status}', NOW())");
                    } else {
                        // 更新分类时，同步上游分类的状态
                        $status = isset($value['status']) ? $value['status'] : $existingCategory['status'];
                        $DB->query("UPDATE qingka_wangke_fenlei SET name='{$fenleiname}', status='{$status}' WHERE id='{$value['fenlei']}'");
                    }
                }
            }
            
            // 删除分类为空的记录
            $beforeCount = $DB->count("SELECT COUNT(*) from qingka_wangke_fenlei WHERE name = '' OR name IS NULL");
            $DB->query("DELETE FROM qingka_wangke_fenlei WHERE name = '' OR name IS NULL");
            $deletedCount = $beforeCount;
            echo "已删除 {$deletedCount} 个空分类名记录<br/>";
            
            // 添加: 删除上游已不存在的分类（除了skipCategories中的分类）
            $upstreamFenleiIds = array();
            foreach ($categories as $value) {
                $upstreamFenleiIds[] = $value['fenlei'];
            }
            
            if (!empty($upstreamFenleiIds)) {
                // 构建NOT IN查询条件，但排除skipCategories中的分类
                $notInCondition = "'" . implode("','", $upstreamFenleiIds) . "'";
                $skipCondition = !empty($skipCategories) ? " AND id NOT IN ('" . implode("','", $skipCategories) . "')" : "";
                
                // 查询需要删除的分类
                $categoriesToDelete = $DB->query("SELECT id, name FROM qingka_wangke_fenlei WHERE id NOT IN ({$notInCondition}){$skipCondition}");
                $deletedCategoryCount = 0;
                $deletedCategoryNames = array();
                
                while ($categoryRow = $DB->fetch($categoriesToDelete)) {
                    $deletedCategoryNames[] = $categoryRow['name'] . '(ID:' . $categoryRow['id'] . ')';
                    $deletedCategoryCount++;
                }
                
                if ($deletedCategoryCount > 0) {
                    // 执行删除操作
                    $DB->query("DELETE FROM qingka_wangke_fenlei WHERE id NOT IN ({$notInCondition}){$skipCondition}");
                    echo "已删除 {$deletedCategoryCount} 个上游不存在的分类: " . implode(", ", $deletedCategoryNames) . "<br/>";
                }
            }
        }
        
        // 收集所有上游商品的ID
        $upstreamProductIds = array();
        foreach ($categories as $value) {
            if (!in_array($value['fenlei'], $skipCategories)) {
                $upstreamProductIds[] = $value['cid'];
            }
        }
        
        // 处理商品数据
        foreach ($categories as $value) {
            if (in_array($value['fenlei'], $skipCategories)) {
                continue;
            }
            
            if (empty($category) || $value['fenlei'] == $category) {
                $price = $value['price'] * $pricee;
                $sort = $numItemsInserted + $numItemsUpdated + 1;
                
                // 应用关键词替换到商品名称和内容
                $name = $value['name'];
                $content = $value['content'];
                
                if ($enableKeywordReplacement) {
                    $name = str_replace(array_keys($keywordReplacements), array_values($keywordReplacements), $name);
                    $content = str_replace(array_keys($keywordReplacements), array_values($keywordReplacements), $content);
                }
                
                $existingProduct = $DB->get_row("SELECT * FROM qingka_wangke_class WHERE docking='{$hid}' AND noun='{$value['cid']}'");
                if ($existingProduct) {
                    // 更新商品时，同步上游商品的状态
                    $status = isset($value['status']) ? $value['status'] : $existingProduct['status'];
                    $DB->query("UPDATE qingka_wangke_class SET price='{$price}', name='{$name}', content='{$content}', status='{$status}' WHERE docking='{$hid}' AND noun='{$value['cid']}'");
                    $numItemsUpdated++;
                } else {
                    // 新增商品时，使用上游商品的状态
                    $status = isset($value['status']) ? $value['status'] : '1';
                    $DB->query("INSERT INTO qingka_wangke_class (name, getnoun, noun, fenlei, queryplat, docking, price, sort, content, addtime, status) 
                                VALUES ('{$name}', '{$value['cid']}', '{$value['cid']}', '{$value['fenlei']}', '$hid', '$hid', '{$price}', '{$sort}', '{$content}', NOW(), '{$status}')");
                    $numItemsInserted++;
                }
            }
        }
        
        // 添加: 删除上游已不存在的商品
        if (!empty($upstreamProductIds)) {
            // 构建NOT IN查询条件
            $notInCondition = "'" . implode("','", $upstreamProductIds) . "'";
            
            // 查询需要删除的商品
            $productsToDelete = $DB->query("SELECT cid, name FROM qingka_wangke_class WHERE docking='{$hid}' AND noun NOT IN ({$notInCondition})");
            $deletedProductCount = 0;
            $deletedProductNames = array();
            
            while ($productRow = $DB->fetch($productsToDelete)) {
                $deletedProductNames[] = $productRow['name'] . '(CID:' . $productRow['cid'] . ')';
                $deletedProductCount++;
            }
            
            if ($deletedProductCount > 0) {
                // 执行删除操作
                $DB->query("DELETE FROM qingka_wangke_class WHERE docking='{$hid}' AND noun NOT IN ({$notInCondition})");
                echo "已删除 {$deletedProductCount} 个上游不存在的商品: " . implode(", ", $deletedProductNames) . "<br/>";
            }
        }
        
        echo "本次对接上架了{$numItemsInserted}个新商品，更新了{$numItemsUpdated}个商品的价格" . ($dockcro == 1 ? "，分类信息已更新" : "") . "</br>";
        exit;
    }
    
    // 处理更新价格操作
    elseif ($act == 'gengxinjiage') {
        $a = $DB->get_row("SELECT * FROM qingka_wangke_huoyuan WHERE hid='{$hid}'");
        if (!$a) {
            jsonReturn(-1, "货源信息不存在");
        }
        
        $data = array("uid" => $a["user"], "key" => $a["pass"]);
        $er_url = "{$a["url"]}/api.php?act=getclass";
        $result = get_url($er_url, $data);
        $result1 = json_decode($result, true);
        
        if (json_last_error() !== JSON_ERROR_NONE || !isset($result1["data"])) {
            jsonReturn(-1, "API 返回数据格式错误或缺失");
        }
        
        $categories = $result1["data"];
        $numItemsUpdated = 0;
        
        // 收集所有上游商品的ID
        $upstreamProductIds = array();
        foreach ($categories as $value) {
            if (!in_array($value['fenlei'], $skipCategories)) {
                $upstreamProductIds[] = $value['cid'];
            }
        }
        
        foreach ($categories as $value) {
            if (in_array($value['fenlei'], $skipCategories)) {
                continue;
            }
            
            $price = $value['price'] * $pricee;
            
            // 应用关键词替换到商品名称和内容
            $name = $value['name'];
            $content = $value['content'];
            
            if ($enableKeywordReplacement) {
                $name = str_replace(array_keys($keywordReplacements), array_values($keywordReplacements), $name);
                $content = str_replace(array_keys($keywordReplacements), array_values($keywordReplacements), $content);
            }
            
            $existingProduct = $DB->get_row("SELECT * FROM qingka_wangke_class WHERE docking='{$hid}' AND noun='{$value['cid']}'");
            
            if ($existingProduct) {
                // 更新商品时，同步上游商品的状态
                $status = isset($value['status']) ? $value['status'] : $existingProduct['status'];
                $DB->query("UPDATE qingka_wangke_class SET price='{$price}', name='{$name}', content='{$content}', status='{$status}' WHERE docking='{$hid}' AND noun='{$value['cid']}'");
                $numItemsUpdated++;
            }
        }
        
        // 添加: 删除上游已不存在的商品
        if (!empty($upstreamProductIds)) {
            // 构建NOT IN查询条件
            $notInCondition = "'" . implode("','", $upstreamProductIds) . "'";
            
            // 查询需要删除的商品
            $productsToDelete = $DB->query("SELECT cid, name FROM qingka_wangke_class WHERE docking='{$hid}' AND noun NOT IN ({$notInCondition})");
            $deletedProductCount = 0;
            $deletedProductNames = array();
            
            while ($productRow = $DB->fetch($productsToDelete)) {
                $deletedProductNames[] = $productRow['name'] . '(CID:' . $productRow['cid'] . ')';
                $deletedProductCount++;
            }
            
            if ($deletedProductCount > 0) {
                // 执行删除操作
                $DB->query("DELETE FROM qingka_wangke_class WHERE docking='{$hid}' AND noun NOT IN ({$notInCondition})");
                echo "已删除 {$deletedProductCount} 个上游不存在的商品: " . implode(", ", $deletedProductNames) . "<br/>";
            }
        }
        
        echo "本次更新了{$numItemsUpdated}个商品的价格和内容" . ($enableKeywordReplacement ? "，并应用了关键词替换" : "") . "</br>";
        exit;
    }
}

// 如果不是通过GET访问或没有提供有效的act参数，执行守护进程逻辑
// 添加调试信息
echo "=== 开始商品同步任务守护进程 ===\n\n";
echo "【配置信息】\n";
echo "网址: {$url}\n";
echo "货源ID: {$hid}\n";
echo "价格倍数: {$pricee}\n";
echo "是否克隆分类: " . ($dockcro == 1 ? "是" : "否") . "\n";
echo "跳过分类: " . implode(", ", $skipCategories) . "\n";
echo "休眠时间: {$sleepTime}秒\n";
echo "默认执行方法: {$defaultMethod}\n";
echo "关键词替换: " . ($enableKeywordReplacement ? "启用" : "禁用") . "\n";
if ($enableKeywordReplacement && count($keywordReplacements) > 0) {
    echo "替换规则:\n";
    foreach ($keywordReplacements as $original => $replacement) {
        echo "  - '{$original}' → '{$replacement}'\n";
    }
}
echo "----------------------------------------\n\n";

// 守护进程主循环
while (true) {
    $startTime = time();
    $currentDateTime = date('Y-m-d H:i:s');
    
    echo "【开始执行】{$currentDateTime}\n";
    echo "----------------------------------------\n";
    
    try {
        // 获取货源信息
        echo "【查询】正在获取货源信息 (HID: {$hid})...\n";
        $a = $DB->get_row("SELECT * FROM qingka_wangke_huoyuan WHERE hid='{$hid}'");
        
        if (!$a) {
            echo "【错误】❌ 货源信息不存在\n";
            echo "----------------------------------------\n";
            echo "【系统】休眠{$sleepTime}秒后重试...\n\n";
            sleep($sleepTime);
            continue;
        }
        
        // 准备API请求数据
        $data = array("uid" => $a["user"], "key" => $a["pass"]);
        $er_url = "{$a["url"]}/api.php?act=getclass";
        
        echo "【请求】正在从源站获取分类数据...\n";
        echo "URL: {$er_url}\n";
        
        // 获取分类数据
        $result = get_url($er_url, $data);
        $result1 = json_decode($result, true);
        
        if (json_last_error() !== JSON_ERROR_NONE || !isset($result1["data"])) {
            echo "【错误】❌ API返回数据格式错误或缺失\n";
            echo "----------------------------------------\n";
            echo "【系统】休眠{$sleepTime}秒后重试...\n\n";
            sleep($sleepTime);
            continue;
        }
        
        $categories = $result1["data"];
        echo "【成功】✅ 获取到" . count($categories) . "个分类数据\n";
        
        $numItemsInserted = 0;
        $numItemsUpdated = 0;
        $keywordsReplaced = 0;
        
        // 根据配置的默认方法执行不同的操作
        if ($defaultMethod == 'yijiankelong') {
            echo "【方法】执行一键克隆操作\n";
            
            // 处理分类数据
            if ($dockcro == 1) {
                echo "【处理】正在更新分类信息...\n";
                
                $categoryCount = 0;
                $categoryInserted = 0;
                $categorySkipped = 0;
                
                // 收集所有上游分类的ID
                $upstreamFenleiIds = array();
                foreach ($categories as $value) {
                    $upstreamFenleiIds[] = $value['fenlei'];
                }
                
                foreach ($categories as $value) {
                    $categoryCount++;
                    
                    // 如果fenlei ID在跳过列表中，则跳过
                    if (in_array($value['fenlei'], $skipCategories)) {
                        $categorySkipped++;
                        continue;
                    }

                    if (empty($category) || $value['fenlei'] == $category) {
                        // 应用关键词替换到分类名称
                        $fenleiname = $value['fenleiname'];
                        if ($enableKeywordReplacement) {
                            $newFenleiname = str_replace(array_keys($keywordReplacements), array_values($keywordReplacements), $fenleiname);
                            if ($newFenleiname !== $fenleiname) {
                                $keywordsReplaced++;
                                $fenleiname = $newFenleiname;
                            }
                        }
                        
                        // 如果分类名为空则跳过
                        if (empty($fenleiname)) {
                            $categorySkipped++;
                            continue;
                        }
                        
                        $existingCategory = $DB->get_row("SELECT * FROM qingka_wangke_fenlei WHERE id='{$value['fenlei']}'");
                        
                        // 插入分类部分
                        if (!$existingCategory) {
                            // 新增分类时，使用上游分类的状态
                            $status = isset($value['status']) ? $value['status'] : '1';
                            $DB->query("INSERT INTO qingka_wangke_fenlei (id, sort, name, status, time) VALUES ('{$value['fenlei']}', '0', '{$fenleiname}', '{$status}', NOW())");
                            $categoryInserted++;
                        } else {
                            // 更新分类时，同步上游分类的状态和名称
                            $status = isset($value['status']) ? $value['status'] : $existingCategory['status'];
                            $DB->query("UPDATE qingka_wangke_fenlei SET name='{$fenleiname}', status='{$status}' WHERE id='{$value['fenlei']}'");
                        }
                    }
                }
                
                // 删除分类为空的记录
                $beforeCount = $DB->count("SELECT COUNT(*) from qingka_wangke_fenlei WHERE name = '' OR name IS NULL");
                $DB->query("DELETE FROM qingka_wangke_fenlei WHERE name = '' OR name IS NULL");
                $deletedCount = $beforeCount;
                echo "【清理】删除了 {$deletedCount} 个空分类名记录\n";
                
                // 添加: 删除上游已不存在的分类（除了skipCategories中的分类）
                if (!empty($upstreamFenleiIds)) {
                    // 构建NOT IN查询条件，但排除skipCategories中的分类
                    $notInCondition = "'" . implode("','", $upstreamFenleiIds) . "'";
                    $skipCondition = !empty($skipCategories) ? " AND id NOT IN ('" . implode("','", $skipCategories) . "')" : "";
                    
                    // 查询需要删除的分类
                    $categoriesToDelete = $DB->query("SELECT id, name FROM qingka_wangke_fenlei WHERE id NOT IN ({$notInCondition}){$skipCondition}");
                    $deletedCategoryCount = 0;
                    $deletedCategoryNames = array();
                    
                    while ($categoryRow = $DB->fetch($categoriesToDelete)) {
                        $deletedCategoryNames[] = $categoryRow['name'] . '(ID:' . $categoryRow['id'] . ')';
                        $deletedCategoryCount++;
                    }
                    
                    if ($deletedCategoryCount > 0) {
                        // 执行删除操作
                        $DB->query("DELETE FROM qingka_wangke_fenlei WHERE id NOT IN ({$notInCondition}){$skipCondition}");
                        echo "【删除】删除了 {$deletedCategoryCount} 个上游不存在的分类: " . implode(", ", $deletedCategoryNames) . "\n";
                    }
                }
                
                echo "【分类】处理: {$categoryCount} | 新增: {$categoryInserted} | 跳过: {$categorySkipped}\n";
            }

            // 收集所有上游商品的ID
            $upstreamProductIds = array();
            foreach ($categories as $value) {
                if (!in_array($value['fenlei'], $skipCategories)) {
                    $upstreamProductIds[] = $value['cid'];
                }
            }

            // 处理商品数据
            echo "【处理】正在更新商品信息...\n";
            
            $productCount = 0;
            $productSkipped = 0;
            
            foreach ($categories as $value) {
                $productCount++;
                
                // 如果fenlei ID在跳过列表中，则跳过
                if (in_array($value['fenlei'], $skipCategories)) {
                    $productSkipped++;
                    continue;
                }

                if (empty($category) || $value['fenlei'] == $category) {
                    $price = $value['price'] * $pricee;
                    $sort = $numItemsInserted + $numItemsUpdated + 1; // 排序字段
                    
                    // 应用关键词替换到商品名称和内容
                    $name = $value['name'];
                    $content = $value['content'];
                    
                    if ($enableKeywordReplacement) {
                        $newName = str_replace(array_keys($keywordReplacements), array_values($keywordReplacements), $name);
                        $newContent = str_replace(array_keys($keywordReplacements), array_values($keywordReplacements), $content);
                        
                        if ($newName !== $name || $newContent !== $content) {
                            $keywordsReplaced++;
                        }
                        
                        $name = $newName;
                        $content = $newContent;
                    }
                    
                    $existingProduct = $DB->get_row("SELECT * FROM qingka_wangke_class WHERE docking='{$hid}' AND noun='{$value['cid']}'");
                    
                    if ($existingProduct) {
                        // 更新商品时，同步上游商品的状态
                        $status = isset($value['status']) ? $value['status'] : $existingProduct['status'];
                        $DB->query("UPDATE qingka_wangke_class SET price='{$price}', name='{$name}', content='{$content}', status='{$status}' WHERE docking='{$hid}' AND noun='{$value['cid']}'");
                        $numItemsUpdated++;
                    } else {
                        // 新增商品时，使用上游商品的状态
                        $status = isset($value['status']) ? $value['status'] : '1';
                        $DB->query("INSERT INTO qingka_wangke_class (name, getnoun, noun, fenlei, queryplat, docking, price, sort, content, addtime, status) 
                                    VALUES ('{$name}', '{$value['cid']}', '{$value['cid']}', '{$value['fenlei']}', '$hid', '$hid', '{$price}', '{$sort}', '{$content}', NOW(), '{$status}')");
                        $numItemsInserted++;
                    }
                }
            }
            
            // 添加: 删除上游已不存在的商品
            if (!empty($upstreamProductIds)) {
                // 构建NOT IN查询条件
                $notInCondition = "'" . implode("','", $upstreamProductIds) . "'";
                
                // 查询需要删除的商品
                $productsToDelete = $DB->query("SELECT cid, name FROM qingka_wangke_class WHERE docking='{$hid}' AND noun NOT IN ({$notInCondition})");
                $deletedProductCount = 0;
                $deletedProductNames = array();
                
                while ($productRow = $DB->fetch($productsToDelete)) {
                    $deletedProductNames[] = $productRow['name'] . '(CID:' . $productRow['cid'] . ')';
                    $deletedProductCount++;
                }
                
                if ($deletedProductCount > 0) {
                    // 执行删除操作
                    $DB->query("DELETE FROM qingka_wangke_class WHERE docking='{$hid}' AND noun NOT IN ({$notInCondition})");
                    echo "【删除】删除了 {$deletedProductCount} 个上游不存在的商品\n";
                }
            }
            
            // 输出处理结果
            echo "【商品】处理: {$productCount} | 新增: {$numItemsInserted} | 更新: {$numItemsUpdated} | 跳过: {$productSkipped}\n";
            if ($enableKeywordReplacement) {
                echo "【替换】执行了 {$keywordsReplaced} 处关键词替换\n";
            }
            echo "【完成】本次对接上架了{$numItemsInserted}个新商品，更新了{$numItemsUpdated}个商品的价格" . ($dockcro == 1 ? "，分类信息已更新" : "") . "\n";
            
        } elseif ($defaultMethod == 'gengxinjiage') {
            echo "【方法】仅执行更新价格操作\n";
            
            // 收集所有上游商品的ID
            $upstreamProductIds = array();
            foreach ($categories as $value) {
                if (!in_array($value['fenlei'], $skipCategories)) {
                    $upstreamProductIds[] = $value['cid'];
                }
            }
            
            // 处理商品数据 - 仅更新价格
            echo "【处理】正在更新商品价格...\n";
            
            $productCount = 0;
            $productSkipped = 0;
            
            foreach ($categories as $value) {
                $productCount++;
                
                // 如果fenlei ID在跳过列表中，则跳过
                if (in_array($value['fenlei'], $skipCategories)) {
                    $productSkipped++;
                    continue;
                }
                
                $price = $value['price'] * $pricee;
                
                // 应用关键词替换到商品名称和内容
                $name = $value['name'];
                $content = $value['content'];
                
                if ($enableKeywordReplacement) {
                    $newName = str_replace(array_keys($keywordReplacements), array_values($keywordReplacements), $name);
                    $newContent = str_replace(array_keys($keywordReplacements), array_values($keywordReplacements), $content);
                    
                    if ($newName !== $name || $newContent !== $content) {
                        $keywordsReplaced++;
                    }
                    
                    $name = $newName;
                    $content = $newContent;
                }
                
                $existingProduct = $DB->get_row("SELECT * FROM qingka_wangke_class WHERE docking='{$hid}' AND noun='{$value['cid']}'");
                
                if ($existingProduct) {
                    // 更新商品时，同步上游商品的状态
                    $status = isset($value['status']) ? $value['status'] : $existingProduct['status'];
                    $DB->query("UPDATE qingka_wangke_class SET price='{$price}', name='{$name}', content='{$content}', status='{$status}' WHERE docking='{$hid}' AND noun='{$value['cid']}'");
                    $numItemsUpdated++;
                }
            }
            
            // 添加: 删除上游已不存在的商品
            if (!empty($upstreamProductIds)) {
                // 构建NOT IN查询条件
                $notInCondition = "'" . implode("','", $upstreamProductIds) . "'";
                
                // 查询需要删除的商品
                $productsToDelete = $DB->query("SELECT cid, name FROM qingka_wangke_class WHERE docking='{$hid}' AND noun NOT IN ({$notInCondition})");
                $deletedProductCount = 0;
                $deletedProductNames = array();
                
                while ($productRow = $DB->fetch($productsToDelete)) {
                    $deletedProductNames[] = $productRow['name'] . '(CID:' . $productRow['cid'] . ')';
                    $deletedProductCount++;
                }
                
                if ($deletedProductCount > 0) {
                    // 执行删除操作
                    $DB->query("DELETE FROM qingka_wangke_class WHERE docking='{$hid}' AND noun NOT IN ({$notInCondition})");
                    echo "【删除】删除了 {$deletedProductCount} 个上游不存在的商品\n";
                }
            }
            
            // 输出处理结果
            echo "【商品】处理: {$productCount} | 更新: {$numItemsUpdated} | 跳过: {$productSkipped}\n";
            if ($enableKeywordReplacement) {
                echo "【替换】执行了 {$keywordsReplaced} 处关键词替换\n";
            }
            echo "【完成】本次更新了{$numItemsUpdated}个商品的价格及内容\n";
        } else {
            echo "【错误】❌ 无效的默认方法: {$defaultMethod}，请设置为 'yijiankelong' 或 'gengxinjiage'\n";
        }
        
        // 计算执行时间
        $endTime = time();
        $executionTime = $endTime - $startTime;
        
        echo "----------------------------------------\n";
        echo "【统计】执行时间: {$executionTime}秒\n";
        echo "----------------------------------------\n";
        
    } catch (Exception $e) {
        echo "【异常】执行过程中出现错误: " . $e->getMessage() . "\n";
        echo "----------------------------------------\n";
    }
    
    echo "【系统】休眠{$sleepTime}秒后继续...\n\n";
    
    // 刷新输出缓冲区
    if (function_exists('ob_flush')) {
        ob_flush();
    }
    if (function_exists('flush')) {
        flush();
    }
    
    // 休眠指定时间
    sleep($sleepTime);
}
?>

